import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Table, Space, Button, Input, Checkbox, Popconfirm, Divider, Drawer, Tabs, message, Select, Row, Col, Modal } from 'antd';
import { SyncOutlined, PlusOutlined, ArrowDownOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import TenantEdit from './components/tenantEdit';
import moment from 'moment';
import MyDataTable from '@/components/MyDataTable';
import request from '@/utils/request';

const apiURL = '/api/services/app/AuthCards/';
const currControl = "Tenant";
const { Search } = Input;
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;
class ViewPage extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            dataSource: [],
            visible: false,
            selectedRowKeys: [],
            pageIndex: 1,
            pageSize: 10,
            totalCount: 0,
            payload: {},
            record: {},
            keywords: '',
            freshNum: 1,
            days: 30,
            count: 100,
            params: {
                keywords: ''
            }
        }
    }
    componentDidMount() {
        this.fetchDatas();
    }
    fetchDatas = () => {
        this.setState({ loading: true });
        const { pageIndex, pageSize, keywords } = this.state;
        this.props.dispatch({
            type: "Abp/getList",
            payload: { SkipCount: (pageIndex - 1) * pageSize, MaxResultCount: pageSize, keywords },
            control: currControl
        }).then(() => {
            var resp = this.props.response;
            if (resp && resp.result) {
                var dataSource = resp.result.items;
                this.setState({ loading: false, dataSource, totalCount: resp.result.totalCount });
            }
        });
    }
    fetchDatas2 = () => {
        const { freshNum, params } = this.state;
        this.setState({ freshNum: freshNum + 1, params });
    }
    handleDelete = (id: number) => {
        this.props.dispatch({
            type: "Abp/delete",
            payload: { id },
            control: currControl
        }).then(() => {
            this.fetchDatas();
        });
    }
    onSelectChange = (selectedRowKeys: any) => {
        this.setState({ selectedRowKeys });
    };
    onSearch = (keywords: any) => {
        this.setState({ keywords }, () => {
            this.fetchDatas();
        });
    }
    onSearch2 = (keywords: any) => {
        const { days, isUse } = this.state;
        var params = {
            keywords,
            days,
            isUse
        }
        this.setState({ params }, () => {
            this.fetchDatas2();
        });
    }
    swithDrawer = (visible: boolean, record = null) => {
        this.setState({ visible, record });
    }
    setRowSelection = (items: any) => {
        this.setState({ authItems: items });
    }
    authCodeCreate = () => {
        const { days, count, freshNum } = this.state;
        const _this = this
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: '确定生成授权码？',
            onOk() {
                _this.setState({ loading2: true });
                request(apiURL + 'CreateCards', {
                    method: 'POST',
                    params: {
                        count,
                        authProd: 'OPERP',
                        authRevNo: '1.0',
                        days
                    },
                }).then((response) => {
                    if (response) {
                        if (response.success) {
                            _this.setState({ freshNum: freshNum + 1 });
                        } else {
                            message.error('生成失败，请联系管理员');
                        }
                        _this.setState({ loading2: false });
                    }
                });
            },
            onCancel() { },
        });

    }
    getCodeCreate = () => {
        const { days, isUse, keywords } = this.state;
        this.setState({ loading2: true });
        request(apiURL + 'GetCodes', {
            method: 'GET',
            params: {
                days, isUse, keywords
            }
        }).then((response) => {
            if (response) {
                if (response.success) {
                    console.log(response.result);
                    var authCodes = "";
                    response.result.forEach((element: any) => {
                        authCodes += element.cardNo + ' ' + element.cardPwd + '\n'
                    });
                    this.setState({ authCodes })
                } else {
                    message.error('获取失败，请联系管理员');
                }
                this.setState({ loading2: false });
            }
        });
    }
    render() {
        const { loading, dataSource, selectedRowKeys, totalCount, pageSize, params, freshNum, loading2, authCodes } = this.state;
        const columns = [
            {
                title: 'ID',
                dataIndex: 'id',
            },
            {
                title: '租户名',
                dataIndex: 'tenancyName',
            },
            {
                title: '别名',
                dataIndex: 'name',
            },
            {
                title: '激活',
                dataIndex: 'isActive',
                render: (text: boolean) => (
                    <Checkbox checked={text} />
                )
            },
            {
                title: '试用期',
                render: (record: any) => record.effectDate ? moment(record.effectDate).format('YYYY-MM-DD') + " 至 " + moment(record.endDate).format('YYYY-MM-DD') : ""
            },
            {
                title: '操作',
                render: (record: any) =>
                    dataSource.length >= 1 ? (
                        <span>
                            <Popconfirm title="确定删除?" onConfirm={() => this.handleDelete(record.id)}>
                                <a>删除</a>
                            </Popconfirm>
                            <Divider type="vertical" />
                            <a onClick={() => this.swithDrawer(true, record)}>编辑</a>
                        </span>
                    ) : null,
            },
        ];
        const column2 = [
            {
                title: '授权码',
                dataIndex: 'cardNo',
            },
            {
                title: '授权产品',
                dataIndex: 'authProd',
            },
            {
                title: '产品版本',
                dataIndex: 'authRevNo',
            },
            {
                title: '授权天数',
                dataIndex: 'authDays',
            },
            {
                title: '已使用',
                dataIndex: 'isUse',
                render: (text: boolean) => <Checkbox checked={text} />
            },
            {
                title: '使用时间',
                render: (record: any) => record.useTime ? moment(record.useTime).format('YYYY-MM-DD hh:mm:ss') : ""
            },
            {
                title: 'ID',
                dataIndex: 'id',

            },
        ]
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        return (
            <PageHeaderWrapper>
                <Card>
                    <Tabs defaultActiveKey="1">
                        <TabPane tab="租户管理" key="1">
                            <Space style={{ marginBottom: 16 }}>
                                <Button type="primary"
                                    onClick={this.fetchDatas}
                                    loading={loading}
                                    icon={<SyncOutlined />} >刷新</Button>
                                <Button type="primary" icon={<PlusOutlined />} onClick={() => this.swithDrawer(true)}>新增</Button>
                                <Search style={{ width: 240 }} placeholder="输入关键词搜索" onSearch={value => this.onSearch(value)} />
                            </Space>

                            <Table
                                rowKey="id"
                                loading={loading}
                                rowSelection={rowSelection}
                                columns={columns}
                                dataSource={dataSource}
                                pagination={{
                                    onChange: page => {
                                        this.setState({ pageIndex: page }, () => {
                                            this.fetchDatas();
                                        });
                                    },
                                    pageSize,
                                    total: totalCount,
                                }} />
                        </TabPane>
                        <TabPane tab="授权码" key="2">
                            <Space style={{ marginBottom: 16 }}>
                                <Button type="primary"
                                    onClick={this.fetchDatas2}
                                    loading={loading}
                                    icon={<SyncOutlined />} >刷新</Button>
                                <Select defaultValue="-1" onChange={(val) => this.setState({ isUse: val })}>
                                    <Option value="1">已使用</Option>
                                    <Option value="0">未使用</Option>
                                    <Option value="-1">全部</Option>
                                </Select>
                                <Select defaultValue="365" onChange={(val) => this.setState({ days: val })}>
                                    <Option value="30">一个月</Option>
                                    <Option value="183">半年</Option>
                                    <Option value="365">一年</Option>
                                    <Option value="1095">三年</Option>
                                    <Option value="1825">五年</Option>
                                    <Option value="3650">十年</Option>
                                </Select>
                                <Select defaultValue="100" onChange={(val) => this.setState({ count: val })}>
                                    <Option value="50">50张</Option>
                                    <Option value="100">100张</Option>
                                    <Option value="500">500张</Option>
                                    <Option value="1000">1000张</Option>
                                    <Option value="3000">3000张</Option>
                                </Select>

                                <Search style={{ width: 240 }} placeholder="输入关键词搜索" onSearch={value => this.onSearch2(value)} />
                            </Space>
                            <Row gutter={16}>
                                <Col span={18}>
                                    <MyDataTable
                                        act="GetList"
                                        columns={column2}
                                        freshNum={freshNum}
                                        pageSize={pageSize}
                                        control="AuthCards"
                                        rowSelection={(items: any) => this.setRowSelection(items)}
                                        params={params}
                                        bordered={false}>
                                    </MyDataTable>
                                </Col>
                                <Col span={6}>
                                    <Space>
                                        <Button type="primary" icon={<PlusOutlined />} onClick={() => this.authCodeCreate()} loading={loading2}>生成授权码</Button>
                                        <Button type="primary" icon={<ArrowDownOutlined />} onClick={() => this.getCodeCreate()} loading={loading2}>获取授权码</Button>
                                    </Space>
                                    <Input.TextArea rows={20} value={authCodes} placeholder="授权码" />
                                </Col>
                            </Row>

                        </TabPane>
                    </Tabs>
                </Card>
                <Drawer
                    width={800}
                    placement="right"
                    closable={false}
                    onClose={() => this.swithDrawer(false)}
                    visible={this.state.visible}
                    destroyOnClose={true}
                >
                    <TenantEdit ParentData={this.state.record} fetchDatas={this.fetchDatas} />
                </Drawer>
            </PageHeaderWrapper>
        )
    }
}
export default connect(({ Abp }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: Abp.currentUser,
}))(ViewPage);